(function() { "use strict";

app
    .service("AuthService", function($q, $http, $state, $window, USER_ROLES, Oauth2, RS, DS, toaster, $translate) {
        var LOCAL_TOKEN_KEY = "_LocalTokenKey";
        var username = "";
        var isAuthenticated = false;
        var role = "";
        var authToken;
        var login_info={
            userType: "",
            userId: "",
            userName: "",
            realName: "",
            age: "",
            sex: "",
            emailAddress: "",
            code: "",
            type: "",
            userRights: "",
            userRoles: "",
            isSystemAdmin : "",
            isMedicalAdmin : "",
            isDoctor : "",
            isUnauthorized : "",
            basicAuthorizationData: "",
            userHeadImageUrl: "",
            headImageUrl: "",
            mediCaseUrl: "",
            mediCaseThumbUrl: "",
            _doctor: ""
        };
        
        function isPrdServer() {
        	if(Oauth2.server.indexOf("www.") >= 0) {
        		return true;
        	}
        	else {
        		return false;
        	}
        }

        function loadUserCredentials() {
            // var token = window.localStorage.getItem(LOCAL_TOKEN_KEY);
            var token = loadData(LOCAL_TOKEN_KEY);
            if (token) {
                useCredentials(token);
            }
        }

        function checkUserCredentials() {
            // var token = window.localStorage.getItem(LOCAL_TOKEN_KEY);
            var token = loadData(LOCAL_TOKEN_KEY);
            if (token) {
                useCredentials(token);
            }
        }

        function storeUserCredentials(token) {
            // window.localStorage.setItem(LOCAL_TOKEN_KEY, token);
            storeData(LOCAL_TOKEN_KEY, token);
            useCredentials(token);
        }

        function isMobile(){
			var ua = navigator.userAgent;
			var app = navigator.appVersion;
			var ipad = ua.match(/(iPad).*OS\s([\d_]+)/);
    		var isIphone = !ipad && ua.match(/(iPhone\sOS)\s([\d_]+)/);
    		var isAndroid = ua.match(/(Android)\s+([\d.]+)/);
    		var isMobile = isIphone || isAndroid; // || true;
			return isMobile;
		}
        
        function storeData(key, data) {
        	if(isMobile()) {
        		$window.localStorage.setItem(key, data);
        	}
        	else {
        		$window.sessionStorage.setItem(key, data);
        	}
        }
        function loadData(key) {
        	if(isMobile()) {
        		return $window.localStorage.getItem(key);
        	}
        	else {
        		return $window.sessionStorage.getItem(key);
        	}
        }
        function removeData(key) {
        	if(isMobile()) {
        		$window.localStorage.removeItem(key);
        	}
        	else {
        		$window.sessionStorage.removeItem(key);
        	}
        }
        
        function useCredentials(token) {
            // username = token.split(".")[0];
            isAuthenticated = true;
            authToken = token;
            // Set the token as header for your requests!
            $http.defaults.headers.common["X-Auth-Token"] = token;
        }

        function destroyUserCredentials() {
        	console.log('logout, destroyUserCredentials...');
            authToken = undefined;
            username = "";
            isAuthenticated = false;
            $http.defaults.headers.common["X-Auth-Token"] = undefined;
            // window.localStorage.removeItem(LOCAL_TOKEN_KEY);
            removeData(LOCAL_TOKEN_KEY);
            // window.localStorage.removeItem("_access_token");
            removeData("_access_token");
        }

        function getLoginfo() {
            return login_info;
        }
        
        function getOpenid() {
        	return login_info.openid;
        }
        
        var login = function(name, pw) {
            return $q(function (resolve, reject) {
                /*if ((name == "admin" && pw == "1") || (name == "user" && pw == "1")) {
                 storeUserCredentials(name + ".yourServerToken");
                 resolve("Login success.");
                 } else {
                 reject("Login Failed.");
                 }*/
                var accessurl = Oauth2.protocol + Oauth2.server + Oauth2.port + Oauth2.context + Oauth2.tokenUrl
                    + "?"+ Oauth2.clientId + "&" + Oauth2.clientSecret + "&" + Oauth2.responseType + "&" + Oauth2.grantType + "&" + Oauth2.userName + name + "&"
                    + Oauth2.password + pw;

                var access_token = "";
                var refresh_token = "";
                var expires_in = "";
                var local_time = "";

                $http({
                    method: "GET",
                    url: accessurl
                }).then(function successCallback(response) {
                    console.log("AS response.data=", response.data);
                    //console.log("response json=" + angular.toJson(response));
                    access_token = response.data.access_token;
                    refresh_token = response.data.refresh_token;
                    expires_in = response.data.expires_in;
                    local_time = (new Date()).getTime();
                    storeUserCredentials(access_token);
					
					storeData("_access_token", access_token);
					storeData("_refresh_token", refresh_token);
					storeData("_expires_in", expires_in);
					storeData("_local_time", local_time);
					
                    accessurl = RS.protocol + RS.server + RS.port+RS.context + RS.markLoginUrl
                        + "?" + RS.access_token+access_token;

                    $http({
                        method: "GET",
                        url: accessurl
                    }).then(function successCallback(response,$scope) {
                    	console.log("RS response.data==========", response.data);
                    	var data = response.data.data[0];
                        login_info.userType = data.userType;
                        login_info.userId = data.userId;
                        login_info.userName = data.userName;
                        login_info.realName = data.realName;
                        login_info.isSystemAdmin = data.isSystemAdmin;
                        login_info.isMedicalAdmin = data.isMedicalAdmin;
                        login_info.isDoctor = data.isDoctor;
                        login_info._doctor = data._doctor;
                        login_info.isUnauthorized = data.isUnauthorized;
                        login_info.age = data.age;
                        login_info.sex = data.sex;
                        login_info.emailAddress = data.emailAddress;
                        login_info.code = response.data.code;
                        login_info.type = data.type;
                        login_info.userRoles = data._userRoles;
                        login_info.userRights = data._userRights;
                        login_info.basicAuthorizationData = data.basicAuthorizationData;
                        login_info.userHeadImageUrl = RS.protocol + RS.server + RS.port+RS.context + "/rest/filesystem/getUserHeadImage?access_token="
                        	+ access_token + "&userId=";
                        // login_info.headImageUrl = RS.protocol + RS.server + RS.port+RS.context + "/rest/filesystem/getHeadImage?access_token="
                        //	+ access_token;
                        if(data.photo_File != null && data.photo_File != '') {
                            login_info.headImageUrl = data.photo_File;
                        }
                        else {
                            login_info.headImageUrl = "images/a0.jpg";
                        }

                        login_info.mediCaseUrl = RS.protocol + RS.server + RS.port+RS.context + "/rest/medicase/getMediCase?access_token="
                        	+ access_token + "&mediCase_Id=";
                        login_info.mediCaseThumbUrl = RS.protocol + RS.server + RS.port+RS.context + "/rest/medicase/getMediCaseThumb?access_token="
                        	+ access_token + "&mediCase_Id=";
                        console.log("RS response end==========", "..." + login_info.basicAuthorizationData);
                        storeData("_basicAuthorizationData", login_info.basicAuthorizationData);
                        
                        // check doctor
						if(login_info.userType == "doctor" && (login_info._doctor == null
							|| login_info._doctor.hosp_Id == 0)) {
							var doctorMsg = $translate.instant("user.needHospital");
							toaster.pop("info", "", doctorMsg, 10000);
						}
                    }, function errorCallback(response) {
                        console.log("response.data=", response.data);
                    });
                    resolve("Login success.");
                }, function errorCallback(response) {
                	console.log("AS response error==========", response);
                    reject("Login Failed.");
                });
            });
        };

		var loginUsingAccessToken = function(access_token) {
            return $q(function (resolve, reject) {
	            var accessurl = RS.protocol + RS.server + RS.port+RS.context + RS.markLoginUrl
	                + "?" + RS.access_token + access_token;
	            console.log("accessurl",accessurl);
	            $http({
	                method: "GET",
	                url: accessurl
	            }).then(function successCallback(response,$scope) {
	            	if(response.data.code == 0) {
	            	    var data = response.data.data[0];
		            	var name = data.userName;
		                local_time = (new Date()).getTime();
		            	storeUserCredentials(access_token);
					
						storeData("_access_token", access_token);
						storeData("_refresh_token", access_token);
						storeData("_expires_in", "3600");
						storeData("_local_time", local_time);
		            
		            	console.log("RS response.data==========", response.data);
		                login_info.userType = data.userType;
		                login_info.userId = data.userId;
		                login_info.userName = data.userName;
		                login_info.realName = data.realName;
		                login_info.isSystemAdmin = data.isSystemAdmin;
		                login_info.isMedicalAdmin = data.isMedicalAdmin;
		                login_info.isDoctor = data.isDoctor;
		                login_info._doctor = data._doctor;
		                login_info.isUnauthorized = data.isUnauthorized;
		                login_info.age = data.age;
		                login_info.sex = data.sex;
		                login_info.emailAddress = data.emailAddress;
		                login_info.code = response.data.code;
		                login_info.type = data.type;
		                login_info.userRoles = data._userRoles;
		                login_info.userRights = data._userRights;
		                login_info.basicAuthorizationData = data.basicAuthorizationData;
		                login_info.userHeadImageUrl = RS.protocol + RS.server + RS.port+RS.context + "/rest/filesystem/getUserHeadImage?access_token="
		                	+ access_token + "&userId=";
		                login_info.headImageUrl = RS.protocol + RS.server + RS.port+RS.context + "/rest/filesystem/getHeadImage?access_token="
		                	+ access_token;
		                login_info.mediCaseUrl = RS.protocol + RS.server + RS.port+RS.context + "/rest/medicase/getMediCase?access_token="
		                	+ access_token + "&mediCase_Id=";
		                login_info.mediCaseThumbUrl = RS.protocol + RS.server + RS.port+RS.context + "/rest/medicase/getMediCaseThumb?access_token="
		                	+ access_token + "&mediCase_Id=";
		                console.log("RS response end==========", "..." + login_info.basicAuthorizationData);
		                storeData("_basicAuthorizationData", login_info.basicAuthorizationData);
	
		                resolve("Login success.");
		            }
		            else {
		            	reject("Login Failed.");
		            }
                }, function errorCallback(response) {
                	console.log("AS response error==========", response);
                    reject("Login Failed.");
                });
	        });
        };
        
        var logout = function() {
            destroyUserCredentials();
        };
        
        var getRsContext = function() {
        	return RS.protocol + RS.server + RS.port + RS.context;
        };

        var getDsContext = function() {
            return DS.protocol + DS.server + DS.port + DS.context;
        };

        var isAuthorized = function(authorizedRoles) {
            if (!angular.isArray(authorizedRoles)) {
                authorizedRoles = [authorizedRoles];
            }
            return (isAuthenticated && authorizedRoles.indexOf(role) !== -1);
        };

        loadUserCredentials();

        return {
            login: login,
            loginUsingAccessToken: loginUsingAccessToken,
            logout: logout,
            isAuthorized: isAuthorized,
            getOpenid: getOpenid,
            getLoginfo: getLoginfo,
            isAuthenticated: function() {return isAuthenticated;},
            username: function() {return username;},
            role: function() {return role;},
            userinfo: getLoginfo,
            getRsContext: getRsContext,
            getDsContext: getDsContext,
            isPrdServer : isPrdServer,
            storeData: storeData,
            loadData: loadData,
            removeData: removeData
        };
    })

    .factory("AuthInterceptor", function ($rootScope, $q, AUTH_EVENTS) {
        return {
            responseError: function (response) {
                $rootScope.$broadcast({
                    401: AUTH_EVENTS.notAuthenticated,
                    403: AUTH_EVENTS.notAuthorized
                }[response.status], response);
                return $q.reject(response);
            }
        };
    })

    .config(function ($httpProvider) {
        $httpProvider.interceptors.push("AuthInterceptor");
    })
    
    .controller("ViewCtrl", function($scope, $state, $http, AuthService) {
	    $scope.logout = function() {
	        AuthService.logout();
	        $state.go("access.login");
	    };
	
	    $scope.performValidRequest = function() {
	        $http.get("http://localhost:9080/valid").then(
	            function(result) {
	                $scope.response = result;
	            });
	    };
	
	    $scope.performUnauthorizedRequest = function() {
	        $http.get("http://localhost:9080/notauthorized").then(
	            function(result) {
	                // No result here..
	            }, function(err) {
	                $scope.response = err;
	            });
	    };
	
	    $scope.performInvalidRequest = function() {
	        $http.get("http://localhost:9080/notauthenticated").then(
	            function(result) {
	                // No result here..
	            }, function(err) {
	                $scope.response = err;
	            });
	    };
	});

})();
